package de.jmda.mview.fx.node.typeshape.relation;

import javafx.beans.property.ObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import de.jmda.fx.node.Line;

/**
 * Relation segments are {@link Line}s that update their {@link
 * #startXProperty()} and {@link #startYProperty()} whenever the value of its
 * bounds in parent property changes.
 *
 * @author roger.jmda@gmail.com
 */
public abstract class RelationSegment extends Line
{
	public RelationSegment(
			ObjectProperty<Point2D> startPoint, ObjectProperty<Point2D> endPoint)
	{
		super(
				startPoint.get().getX(), startPoint.get().getY(),
				  endPoint.get().getX(),   endPoint.get().getY());

		boundsInParentProperty().addListener(new PointUpdater<Bounds>(startPoint));
		boundsInParentProperty().addListener(new PointUpdater<Bounds>(endPoint));
	}

	private class PointUpdater<T extends Bounds> implements
	    ChangeListener<Bounds>
	{
		private ObjectProperty<Point2D> point;

		public PointUpdater(ObjectProperty<Point2D> point)
    {
			this.point = point;
    }

		@Override
    public void changed(ObservableValue< ? extends Bounds> observable,
        Bounds oldValue, Bounds newValue)
    {
			point.set(new Point2D(startXProperty().get(), startYProperty().get()));
    }
	}
}